import tkinter as tk
import csv
import re
import os
from tkinter import messagebox
from collections import defaultdict
from tkinter import scrolledtext, PanedWindow, filedialog
from myCryption import validate_license_code


def generate_bta_processing_code(bta_data):
    output_code = ""
    if not bta_data:
        return output_code

    # 用于存储已处理的 switch_var
    processed_switches = set()

    # 用于记录每个 switch_var 的重复数组名字
    switch_duplicate_names = {}

    output_code += "static int mipi_bta_process(uint32_t data, uint32_t data_bak, uint32_t data_bak2)"
    output_code += "\n{"
    output_code += "\n  uint8_t data0 = 0, data1 = 0, data2 = 0, data3 = 0;"
    output_code += "\n  data0 = (data >> 0)  &  0xff;"
    output_code += "\n  data1 = (data >> 8)  &  0xff;"
    output_code += "\n  data2 = (data >> 16) &  0xff;"
    output_code += "\n  data3 = (data >> 24) &  0xff;"
    output_code += '\n  \\\\printf("BT1:0x%x, T2:0x%x, T3:0x%x\\r\\n", data, data_bak, data_bak2);'
    output_code += "\n"
    output_code += "\n  switch(data0)"
    output_code += "\n  {"

    # 遍历 bta_data
    for item in bta_data:
        # 解析数组名，假设数组名格式为 BTA_XX_YY
        array_name_parts = item.split("_")
        if len(array_name_parts) < 3:
            continue

        switch_var = array_name_parts[1]  # 第一个 switch 的 case 变量
        case_var = array_name_parts[2]  # 第二个 switch 的 case 变量

        # 如果该 switch_var 还没处理过，则生成外层 switch 代码
        if switch_var not in processed_switches:
            if processed_switches:
                # 如果已经有处理过的 switch_var，先闭合上一个 case 的大括号
                output_code += "    }\n"
            processed_switches.add(switch_var)
            output_code += "\n"
            output_code += f"    case 0x{switch_var}:\n"
            output_code += "    {\n"  # 开始外层 case 的大括号

            # 生成内层 switch(data1) 结构，根据 case_var 动态生成 case 分支
            output_code += "      switch(data1)\n"
            output_code += "      {\n"

            # 用于记录已经处理过的 case_var
            processed_cases = set()

            # 动态生成 case 分支
            for inner_item in bta_data:
                inner_array_name_parts = inner_item.split("_")
                if len(inner_array_name_parts) < 3:
                    continue
                inner_switch_var = inner_array_name_parts[1]
                inner_case_var = inner_array_name_parts[2]
                if inner_switch_var == switch_var:

                    # 记录重复的数组名字
                    if inner_case_var in switch_duplicate_names.get(switch_var, set()):
                        output_code += f"            // WARNING: '{inner_item}'BTA数组与其他数组为同一个指令头，但回复内容不同请自行做兼容!\n"
                    else:
                        switch_duplicate_names.setdefault(switch_var, set()).add(inner_case_var)

                    if inner_case_var not in processed_cases:
                        processed_cases.add(inner_case_var)
                        output_code += f"        case 0x{inner_case_var}:\n"
                        output_code += f"            device_cmd_response({inner_item}, sizeof({inner_item}));\n"
                        # output_code += f"            // printf({inner_item} bta: 0x%x\\n, data)\n"
                        output_code += f"            break;\n"


            output_code += "        default:\n"
            output_code += f"            // printf(other {switch_var} bta: 0x%x\\n, data)\n"
            output_code += "            break;\n"
            output_code += "      }\n"
            output_code += "      break;\n"  # 跳出外层 switch(data1)

    if processed_switches:
        output_code += "    }\n"  # 闭合最后一个 case 的大括号

    output_code += "\n"
    output_code += "    default:\n"
    output_code += '        // printf(other bta: 0x%x\\n, data)\n'
    output_code += "        break;\n"

    output_code += "  }\n"
    output_code += "}\n"

    return output_code


def extract_array_names(bta_data):
    array_names = []
    for item in bta_data:
        # 寻找形如 "uint32_t BTA_06_04" 或 "uint32_t BTA_06_04_1" 的数组名
        start_idx = item.find("BTA_")
        if start_idx != -1:
            end_idx = item.find(" ", start_idx)
            if end_idx == -1:
                end_idx = item.find("=", start_idx)
            if end_idx != -1:
                array_name = item[start_idx:end_idx].strip()
                array_names.append(array_name)
    return array_names


def process_bta_data(bta_data):
    array_counts = defaultdict(int)
    unique_bta_data = []

    # 使用字典来存储已经处理过的数组内容
    seen_arrays = defaultdict(set)

    for item in bta_data:
        array_name_start = item.find("BTA_")  # 找到数组名的起始位置
        if array_name_start != -1:
            array_name_end = item.find(" ", array_name_start)  # 找到数组名的结束位置
            if array_name_end != -1:
                array_name = item[array_name_start:array_name_end]  # 提取数组名部分
                array_content = item[array_name_end + 1:].strip()  # 提取数组内容部分

                if array_content in seen_arrays[array_name]:
                    # 如果数组名和内容已经存在于 seen_arrays 中，则不添加到 unique_bta_data 中
                    continue

                seen_arrays[array_name].add(array_content)

                if array_name in array_counts:
                    array_counts[array_name] += 1
                    new_array_name = f"{array_name}_{array_counts[array_name]}"
                    unique_bta_data.append(item.replace(array_name, new_array_name, 1))
                else:
                    array_counts[array_name] = 0
                    unique_bta_data.append(item)
            else:
                unique_bta_data.append(item)
        else:
            unique_bta_data.append(item)

    return unique_bta_data


def select_files_and_process():
    file_paths = filedialog.askopenfilenames(
        title="选择一个或多个CSV文件",
        filetypes=[("CSV Files", "*.csv")]
    )
    if file_paths:
        # 创建 Tkinter 窗口
        root = tk.Tk()
        root.withdraw()  # 隐藏主窗口

        # 创建输出文本框窗口
        output_window = tk.Toplevel(root)
        output_window.title("处理结果")
        output_textbox = scrolledtext.ScrolledText(output_window, wrap=tk.WORD, height=30, width=100)
        output_textbox.pack(fill=tk.BOTH, expand=True)  # 自适应大小

        # 处理选择的文件
        read_csv_and_process_bta(output_textbox, file_paths)

        # 运行 Tkinter 事件循环
        root.mainloop()


def read_csv_and_process_bta(output_textbox, file_paths):
    bta_data = []
    debug_info = []  # 用于存储调试信息
    dt_index = None
    d0_index = None
    wc_index = None  # 添加了 WC 的索引
    lp_bta_count = 0  # 记录 LP_BTA 的计数
    processing_lp_bta = False  # 标记是否正在处理 LP_BTA 的下一行数据
    pps_collecting = False
    pps_data =[]
    pps_11_flag = False
    wc_value_str = ''
    for file_path in file_paths:
        file_name = os.path.splitext(os.path.basename(file_path))[0]  # 获取文件名，不包括扩展名
        try:
            with open(file_path, 'r', encoding='utf-8-sig') as csvfile:
                csvreader = csv.reader(csvfile)
                header = next(csvreader)  # 读取标题行

                # 确定 DT、D0 和 WC 的索引
                if header:
                    dt_index = header.index("DT")
                    d0_index = header.index("D0")
                    wc_index = header.index("WC")

                previous_row = None
                for row_num, row in enumerate(csvreader, start=2):  # 行号从第二行开始计数
                    debug_info.append(f"处理第 {row_num} 行数据...")

                    mode = row[1].strip().strip('="')  # 去除额外的等号和引号
                    dt_value = row[dt_index].strip().strip('="') if dt_index is not None else ''
                    d0_value = row[d0_index].strip().strip('="') if d0_index is not None else ''
                    data_values = [val.strip() for val in row[6:14] if val.strip() and val.strip().startswith("0x")]
                    wc_value_str = row[wc_index].strip().strip('="')
                    # print(wc_value_str)
                    debug_info.append(f"Mode: {mode}, DT: {dt_value}, D0: {d0_value}")

                    if processing_lp_bta:
                        # 处理 LP_BTA 的下一行数据
                        if mode == 'LP_ESC':
                            # 提取 DCS
                            dcs_value = row[dt_index].strip().strip('="')[-3:-1] if len(row) > 6 else ''
                            if dcs_value:
                                # 提取 WC
                                if wc_value_str == ' ':
                                    wc_value = '0002'
                                else:
                                    wc_value = wc_value_str[-4:]

                                # 检查 WC 是否有效
                                if all(c in '0123456789abcdefABCDEF' for c in wc_value) and len(wc_value) == 4:
                                    wc_value_int = int(wc_value, 16)

                                    # 获取后续数据
                                    additional_data = [f"0x{dcs_value}"]
                                    additional_data.extend([wc_value])
                                    additional_data.extend([val.strip().strip('="') for val in row[7:7 + wc_value_int] if
                                                            val.strip() and val.strip()])

                                    # 构建数组名称和数据
                                    array_name = f"uint32_t BTA_{previous_dt_value}_{previous_d0_value}"

                                    if wc_value_int > 2:
                                        long_package_data = []
                                        wc1 = wc_value[0:2] if len(wc_value) > 1 else '00'
                                        wc0 = wc_value[2:4] if len(wc_value) > 3 else '00'
                                        first_line_data = f"00{wc1}{wc0}{dcs_value}"
                                        long_package_data.append(first_line_data)

                                        for i in range(2, len(additional_data), 4):
                                            chunk = additional_data[i:i + 4]
                                            if len(chunk) < 4:
                                                chunk = ['00'] * (4 - len(chunk)) + chunk
                                            chunk = ['0x'] + chunk
                                            long_package_data.append(''.join(chunk))

                                        array_content = ',\n'.join(long_package_data)
                                        bta_data.append(f"{array_name} = {{\n0x{array_content}\n}}")
                                        debug_info.append(f"提取的数组名称: {array_name}")

                                    else:
                                        short_package_data = ['\n''0x00', '00']
                                        if len(additional_data) > 2:
                                            short_package_data.append(additional_data[2])
                                        else:
                                            short_package_data.append('00')
                                        short_package_data.append(dcs_value + '\n')

                                        array_content = ''.join(short_package_data)

                                        bta_data.append(f"{array_name} = {{{array_content}}}")
                                        debug_info.append(f"提取的数组名称: {array_name}")

                                else:
                                    debug_info.append(f"错误：无效的十六进制字符 '{wc_value}' 或长度不为4")

                            processing_lp_bta = False

                    if mode == 'LP_BTA':
                        lp_bta_count += 1
                        debug_info.append(f"LP_BTA 计数: {lp_bta_count}")

                        if lp_bta_count % 2 != 0:
                            if previous_row:
                                previous_dt_value = previous_row[dt_index].strip().strip('="')[
                                                    -3:-1] if dt_index is not None else ''
                                previous_d0_value = previous_row[d0_index].strip().strip(
                                    '="') if d0_index is not None else ''
                                debug_info.append(f"Previous DT value: {previous_dt_value}")
                                debug_info.append(f"Previous D0 value: {previous_d0_value}")

                                if previous_dt_value and previous_d0_value:
                                    processing_lp_bta = True
                                else:
                                    debug_info.append("未找到 DT 或 D0 中的数字部分")
                    # # 检查是否为 PPS 数据
                    # if wc_value_str:
                    #     print("sec" + wc_value_str)
                    if any(val in dt_value for val in ['39', '0A']) and any(val in wc_value_str for val in ['80', '59', '81', '5A', '89']):
                        pps_collecting = True
                        # print("pps get 1")
                        pps_data_list = []

                    if pps_collecting:
                        # 读取后续数据（最多100个数据，跨行读取）
                        pps_values = [row[7:14]]  # 假设数据在第6到14列
                        if '11' == row[7].strip().strip('=\"'):
                            # print('11')
                            pps_11_flag = True
                        # print(pps_values)
                        for _ in range(14):  # 最多读取12行数据
                            try:
                                next_row = next(csvreader)
                                pps_values.append(next_row[7:14])
                                # print(next_row[7:14])
                            except StopIteration:
                                break
                        # 扁平化数据并格式化
                        flattened_values = [f"0x{val.strip().strip('=\"')}," for sublist in pps_values for val in
                                            sublist if val.strip()]

                        # 调试输出
                        # print("原始数据：", pps_values)
                        # print("扁平化后的数据：", flattened_values)

                        # if len(flattened_values) > 120:
                        #     if pps_11_flag:
                        #         flattened_values = flattened_values[:128]
                        #         print("pps_11_flag")
                        #     else:
                        #         flattened_values = flattened_values[1:129]
                        # else:
                        if pps_11_flag:
                            flattened_values = flattened_values[:-1]
                            print("pps_11_flag")
                        else:
                            flattened_values = flattened_values[1:-1]

                        # 计算当前元素数量
                        current_count = len(flattened_values)
                        # 补充到 128 个元素 方便复制粘贴
                        if current_count < 128:
                            # 计算需要补充多少个
                            num_to_add = 128 - current_count
                            # 补充 0x00
                            flattened_values.extend(["0x00,"] * num_to_add)
                        # 每八个数据一组
                        grouped_values = [flattened_values[i:i + 8] for i in range(0, len(flattened_values), 8)]

                        # 格式化每行
                        formatted_pps_data = '\n'.join([' '.join(group) for group in grouped_values])
                        pps_data.append(f"PPS 数据 ({file_name}):\n{formatted_pps_data}")
                        pps_collecting = False

                    debug_info.append(f"当前行数据 - Mode: {mode}, DT: {dt_value}, D0: {d0_value}, 数据: {', '.join(data_values)}")

                    previous_row = row

            bta_data = process_bta_data(bta_data)

            output_textbox.delete('1.0', tk.END)
            if bta_data:
                output_textbox.insert(tk.END, "提取的 BTA 数据:\n")
                for item in bta_data:
                    output_textbox.insert(tk.END, item + "\n")
            else:
                output_textbox.insert(tk.END, "未找到符合条件的 BTA 数据。\n")

            if pps_data:
                # print("pps get")
                #创建新的窗口
                pps_window = tk.Toplevel()
                pps_window.title("PPS 数据")

                # 创建 Text 组件
                pps_textbox = tk.Text(pps_window, wrap=tk.WORD)
                # 自适应大小
                pps_textbox.pack(fill=tk.BOTH, expand=True)

                # 插入 PPS 数据
                for item in pps_data:
                    pps_textbox.insert(tk.END, item + "\n")
                # 插入格式化后的 PPS 数据
                # pps_textbox.insert(tk.END, formatted_pps_data)

                # 可选：为窗口添加滚动条（如果需要）
                scrollbar = tk.Scrollbar(pps_window, orient=tk.VERTICAL, command=pps_textbox.yview)
                scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
                pps_textbox.config(yscrollcommand=scrollbar.set)

                # 更新窗口大小
                pps_window.update_idletasks()

        except FileNotFoundError:
            output_textbox.delete('1.0', tk.END)
            output_textbox.insert(tk.END, f"错误：找不到文件 {file_path}\n")
        except Exception as e:
            output_textbox.delete('1.0', tk.END)
            output_textbox.insert(tk.END, f"错误：{str(e)}\n")
    # 提取数组名并展示处理后的代码
    array_names = extract_array_names(bta_data)
    bta_code = generate_bta_processing_code(array_names)

    code_window = tk.Toplevel()
    code_window.title("生成的bta代码")
    code_textbox = tk.Text(code_window, wrap=tk.WORD, height=30, width=100)
    code_textbox.insert(tk.END, bta_code)
    code_textbox.pack(fill=tk.BOTH, expand=True)  # 自适应大小


# 处理按钮点击事件：选择并处理 CSV 文件
def handle_read_csv(output_textbox, file_path):
    output_textbox.delete('1.0', tk.END)  # 清空文本框

    try:
        with open(file_path, 'r', newline='', encoding='utf-8-sig') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                output_textbox.insert(tk.END, ', '.join(row) + '\n')

        if output_textbox.get('1.0', tk.END).strip() == '':
            output_textbox.insert(tk.END, "未找到数据或文件为空。\n")

    except FileNotFoundError:
        output_textbox.insert(tk.END, f"错误：找不到文件 {file_path}\n")
    except Exception as e:
        output_textbox.insert(tk.END, f"错误：{str(e)}\n")


def open_csv_file_and_process(output_textbox):
    file_paths = filedialog.askopenfilenames(
        title="选择一个或多个CSV文件",
        filetypes=[("CSV Files", "*.csv")]
    )
    if file_paths:
        read_csv_and_process_bta(output_textbox, file_paths)


# 函数：提取特定命令数据
def extract_specific_command_data(text, command_name, header_value=None, index_start=0, start_find_value="(",
                                  end_find_value=")", include_non_hex=False):
    # 检查并处理默认参数
    if text is None:
        raise ValueError("参数 'text' 不能为空")

    # 初始化返回的数据
    extracted_data = []

    lines = text.splitlines()
    extracted_data = []
    index = index_start
    print(command_name + start_find_value + end_find_value)
    # print(start_find_value)
    # print(end_find_value)
    for line in lines:
        print(line)
        if line.startswith(command_name):
            # 使用用户提供的 start_find_value 和 end_find_value
            start_find_pos = line.find(start_find_value)
            end_find_pos = line.find(end_find_value, start_find_pos)
            print(start_find_pos + end_find_pos)
            if start_find_pos == -1 or end_find_pos == -1:
                print('continue')
                continue

            start_idx = start_find_pos + 1
            end_idx = end_find_pos

            if end_idx <= start_idx:
                continue

            params_str = line[start_idx:end_idx].strip()
            params = params_str.split(';,')

            # 替换 ';' 为 ',' 后生成 hex_data 列表
            hex_data_raw = [p.strip() for p in params]
            hex_data_replaced = [data.replace(';', ',') for data in hex_data_raw]

            # 扁平化 hex_data_replaced 列表并移除空值
            flat_hex_data = [item for sublist in [data.split(',') for data in hex_data_replaced] for item in sublist if
                             item.strip()]

            # 筛选出以 0x 开头的数据
            if include_non_hex:
                hex_data = flat_hex_data
            else:
                hex_data = [data for data in flat_hex_data if data.startswith("0x")]

            if header_value is None:
                header_value = 0x29  # 默认指令头为0x29

            array_name = f"cmd{index}"
            data_length = len(hex_data)
            array_content = [f"0x{header_value:02X}", f"0x{data_length:02X}"] + ["0x00"] + hex_data
            array_definition = f"static uint8_t {array_name}[] = {{{', '.join(array_content)}}};"
            extracted_data.append(array_definition)
            index += 1

    return extracted_data


def extract_gui():
    def extract_data():
        input_text = input_textbox.get("1.0", tk.END)
        command_name = command_entry.get().strip()
        header_value_str = header_entry.get().strip()
        index_start_str = index_entry.get().strip()
        start_find_value = start_find_entry.get().strip()
        end_find_value = end_find_entry.get().strip()
        include_non_hex = include_non_hex_var.get()

        if not command_name:
            command_name = "GEN_WR"
        # 使用默认值如果用户未输入值
        if not start_find_value:
            start_find_value = "("
        if not end_find_value:
            end_find_value = ")"

        if header_value_str.startswith("0x"):
            header_value = int(header_value_str, 16)
            print(header_value)
        else:
            header_value = None

        if index_start_str.isdigit():
            index_start = int(index_start_str)
        else:
            index_start = 0  # 默认起始值为0

        extracted_data = extract_specific_command_data(input_text, command_name, header_value, index_start,
                                                       start_find_value, end_find_value, include_non_hex)

        output_textbox.delete("1.0", tk.END)
        for data in extracted_data:
            output_textbox.insert(tk.END, data + "\n")

    extract_window = tk.Toplevel()
    extract_window.title("提取指定命令数据")

    paned_window = PanedWindow(extract_window, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=5)
    paned_window.pack(fill=tk.BOTH, expand=True)

    left_frame = tk.Frame(extract_window)
    right_frame = tk.Frame(extract_window)

    paned_window.add(left_frame)
    paned_window.add(right_frame)

    input_label = tk.Label(left_frame, text="请粘贴要处理的命令文本:")
    input_label.pack(fill=tk.X, padx=5, pady=5)

    input_textbox = scrolledtext.ScrolledText(left_frame, width=40, height=15)
    input_textbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    command_label = tk.Label(left_frame, text="请输入要提取的命令名称（例如：GEN_WR）： 留空则默认为GEN_WR")
    command_label.pack(fill=tk.X, padx=5, pady=5)

    command_entry = tk.Entry(left_frame)
    command_entry.pack(fill=tk.X, padx=5, pady=5)

    header_label = tk.Label(left_frame, text="请输入指令头的十六进制数值（例如：0x29），留空则默认为0x29:")
    header_label.pack(fill=tk.X, padx=5, pady=5)

    header_entry = tk.Entry(left_frame)
    header_entry.pack(fill=tk.X, padx=5, pady=5)

    index_label = tk.Label(left_frame, text="请输入起始索引值（例如：0），默认为0:")
    index_label.pack(fill=tk.X, padx=5, pady=5)

    index_entry = tk.Entry(left_frame)
    index_entry.pack(fill=tk.X, padx=5, pady=5)

    start_find_label = tk.Label(left_frame, text="请输入有效数据最左边的符号 查找的值（例如：'GEN_WR(0xFF,0x80,0x57) 则输入(或则R(，）默认为'(':")
    start_find_label.pack(fill=tk.X, padx=5, pady=5)

    start_find_entry = tk.Entry(left_frame)
    start_find_entry.pack(fill=tk.X, padx=5, pady=5)

    end_find_label = tk.Label(left_frame, text="请输入有效数据最右边的符号 查找的值（例如：'GEN_WR(0xFF,0x80,0x57) 则输入)或则;，）默认为')':")
    end_find_label.pack(fill=tk.X, padx=5, pady=5)

    end_find_entry = tk.Entry(left_frame)
    end_find_entry.pack(fill=tk.X, padx=5, pady=5)

    include_non_hex_var = tk.BooleanVar()
    include_non_hex_check = tk.Checkbutton(left_frame, text="包含不以 '0x' 开头的数据", variable=include_non_hex_var)
    include_non_hex_check.pack(pady=5)

    extract_button = tk.Button(left_frame, text="提取数据", command=extract_data)
    extract_button.pack(pady=10)

    output_label = tk.Label(right_frame, text="提取结果:")
    output_label.pack(fill=tk.X, padx=5, pady=5)

    output_textbox = scrolledtext.ScrolledText(right_frame, width=40, height=15)
    output_textbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    extract_window.mainloop()


# 转换数据界面
def convert_gui():
    def convert_data():
        hex_data = hex_textbox.get("1.0", tk.END)
        converted_data = convert_hex_to_array(hex_data)

        converted_textbox.delete("1.0", tk.END)
        for data in converted_data:
            converted_textbox.insert(tk.END, data + "\n")

    convert_window = tk.Toplevel()
    convert_window.title("PPS 十六进制数据转换为数组")

    paned_window = PanedWindow(convert_window, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=5)
    paned_window.pack(fill=tk.BOTH, expand=True)

    left_frame = tk.Frame(convert_window)
    right_frame = tk.Frame(convert_window)

    paned_window.add(left_frame)
    paned_window.add(right_frame)

    hex_label = tk.Label(left_frame, text="请粘贴要转换的PPS 十六进制数据（每行以空格分隔）:")
    hex_label.pack(fill=tk.X, padx=5, pady=5)

    hex_textbox = scrolledtext.ScrolledText(left_frame, width=40, height=15)
    hex_textbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    convert_button = tk.Button(left_frame, text="转换数据", command=convert_data)
    convert_button.pack(pady=10)

    converted_label = tk.Label(right_frame, text="转换后的数据:")
    converted_label.pack(fill=tk.X, padx=5, pady=5)

    converted_textbox = scrolledtext.ScrolledText(right_frame, width=40, height=15)
    converted_textbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)


def create_main_gui():
    global output_textbox
    root = tk.Tk()

    root.title("数据处理工具")

    extract_button = tk.Button(root, text="提取指定命令数据", command=extract_gui)
    extract_button.pack(pady=20)

    convert_button = tk.Button(root, text="PPS/十六进制数据转换为数组", command=convert_gui)
    convert_button.pack(pady=20)

    excel_button = tk.Button(root, text="从 CSV 读取数据 提取BTA(Ctrl多选CSV)\n可提取PPS", command=lambda: open_csv_file_and_process(output_textbox))
    excel_button.pack(pady=20)

    # 创建 output_textbox
    output_textbox = scrolledtext.ScrolledText(root, width=40, height=15)
    output_textbox.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
    root.mainloop()


def read_verification_code(filename):
    if os.path.exists(filename):
        with open(filename, 'r') as f:
            verification_code = f.read().strip()
            if verification_code:
                return verification_code
            else:
                return None
    else:
        return None


def save_verification_code(filename, verification_code):
    print("正在写入" + verification_code)
    with open(filename, 'w') as f:
        f.write(verification_code)
        messagebox.showinfo("保存成功", "校验码已保存。")


def input_verification_code(file_path):
    def save_code():
        code = entry.get().strip()
        print("code" + code)
        if code:
            if verify_code(code):
                save_verification_code(file_path, code)
                window.destroy()
            else:
                messagebox.showerror("校验失败", "校验码错误，请重新输入。")
        else:
            messagebox.showerror("错误", "请输入校验码。")

    def verify_code(code):
        if code:
            verification_state = validate_license_code(code)
        else:
            local_verification_code = read_verification_code(file_path)
            verification_state = validate_license_code(local_verification_code)
            print("re read" + local_verification_code)
        if verification_state:
            return True
        else:
            return False

    window = tk.Tk()
    window.title("输入校验码")

    label = tk.Label(window, text="请输入校验码：")
    label.pack(pady=10)

    entry = tk.Entry(window, show='*')
    entry.pack(pady=10)

    button = tk.Button(window, text="保存", command=save_code)
    button.pack(pady=10)

    window.mainloop()
